<!--  -->
<template>
  <div class="seo-baidu-api">
    <div class="noticeShowM">
      <p>设置后，系统将会每天将前一天发布的文章，产品栏目推送至百度。</p>
    </div>
    <el-collapse v-model="activeName">
      <el-collapse-item name="1">
        <template slot="title">
          <div :class="{'tempalte-title': true, 'active': activeName.indexOf('1') > -1}">第一步：注册百度站长账号</div>
        </template>
        <div class="content-p">
          <p>注册：<a href="https://ziyuan.baidu.com/" target="_blank">https://ziyuan.baidu.com/</a></p>
        </div>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template slot="title">
          <div :class="{'tempalte-title': true, 'active': activeName.indexOf('2') > -1}">第二步：添加站点</div>
        </template>
        <div class="content-p">
          <p>百度站长 -> 用户中心 ->添加站点</p>
          <p><img :src="baiduimg1" alt="添加站点" /></p>
        </div>
      </el-collapse-item>
      <el-collapse-item name="3">
        <template slot="title">
          <div :class="{'tempalte-title': true, 'active': activeName.indexOf('3') > -1}">第三步：获取token</div>
        </template>
        <div class="content-p">
          <p>复制下图红色区域的值</p>
          <p><img :src="baiduimg2" alt="获取token" /></p>
        </div>
      </el-collapse-item>
      <el-collapse-item name="4">
        <template slot="title">
          <div :class="{'tempalte-title': true, 'active': activeName.indexOf('4') > -1}">第四步：设置域名和token</div>
        </template>
        <div class="content-p" v-loading="bandleTokenLoading">
          <el-form :model="form">
            <el-form-item label="选择域名：" :label-width="formLabelWidth" class="requireStar">
              <el-select size="medium" v-model="form.domainId" placeholder="请选择" style="width:300px;">
                <el-option v-for="(item, index) in domains" :key="index" :label="item.domainName" :value="item.id">
                </el-option>
              </el-select>
              <span class="note">请确保选择的域名与百度添加的站点域名一致<span
                  :style="bandleDomainStatusStyle">{{bandleDomainStatusHtml}}</span></span>
            </el-form-item>
            <el-form-item label="token值：" :label-width="formLabelWidth">
              <el-input v-model="form.zztoken" size="medium" placeholder="请输入" maxlength="1000" style="width:300px;">
              </el-input>
            </el-form-item>
          </el-form>
          <div class="group-button">
            <!-- <el-button type="primary" @click="onSubmitData" size="small">更 新</el-button> -->
            <el-button v-if="form && form.domainId && form.domainId > 0" type="primary" @click="onSubmitTest"
              size="small">保存并测试</el-button>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item name="5">
        <template slot="title">
          <div :class="{'tempalte-title': true, 'active': activeName.indexOf('4') > -1}">Finish：查看推送记录<span
              class="note">(仅获取最近30条推送记录)</span></div>
        </template>
        <div class="content-p">
          <el-table :data="tableData" style="width: 100%" v-loading="loading">
            <el-table-column prop="domain.domainName" label="推送域名">
            </el-table-column>
            <el-table-column prop="baiduUrls.createAt" label="推送时间" align="center">
              <template slot-scope="scope">
                {{scope.row.baiduUrls.createAt | dateformat('YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column prop="baiduUrls.urlsAllTotal" label="推送条数" align="center">
            </el-table-column>
            <el-table-column prop="baiduUrls.urlsSucessTotal" label="成功条数" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button @click="viewInfo(scope.row.baiduUrls.id)" type="text " size="small">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align: right;margin-top:10px;" v-if="totalnum > pagesize">
            <el-pagination small layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pagesize"
              :total="totalnum">
            </el-pagination>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-dialog v-if='viewData' :title="$moment(viewData.baiduUrls.createAt).format('YYYY-MM-DD') + '推送详情'"
      :visible.sync="dialogTableVisible" width="800" class="dialogDetail" @closed="close">
      <div v-if='viewData && viewData.baiduUrls.status === 1'>
        <div class="totalBox">
          <div class="item">
            <div class="num">{{viewData.baiduUrls.urlsAllTotal}}</div>
            <p>推送条数</p>
          </div>
          <div class="item">
            <div class="num">{{viewData.baiduUrls.urlsSucessTotal}}</div>
            <p>成功推送</p>
          </div>
          <div class="item">
            <div class="num">{{viewData.baiduUrls.urlsNotValidTotal}}</div>
            <p>不合法URL</p>
          </div>
          <div class="item">
            <div class="num">{{viewData.baiduUrls.urlsNotSameSiteTotal}}</div>
            <p>非本站URL</p>
          </div>
        </div>
        <el-tabs v-model="activeNames">
          <el-tab-pane label="成功推送" name="1">
            <BaiduAPIDatatable :dataTable='viewData.baiduUrls.urlsSucess' />
          </el-tab-pane>
          <el-tab-pane label="不合法URL" name="2">
            <BaiduAPIDatatable :dataTable='viewData.baiduUrls.urlsNotValid' />
          </el-tab-pane>
          <el-tab-pane label="非本站URL" name="3">
            <BaiduAPIDatatable :dataTable='viewData.baiduUrls.urlsNotSameSite' />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-if='viewData && viewData.baiduUrls.status === 2' class="errorMessage">
        <div class="hh">推送失败错误描述</div>
        <div>{{viewData.baiduUrls.message}}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button size="small" @click="exportToExcel">导出EXCEL</el-button> -->
        <el-button size="small" type="primary" @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baiduimg1 from '@/assets/baiduimg1.jpg'
import baiduimg2 from '@/assets/baiduimg2.jpg'
import BaiduAPIDatatable from '@/components/main/user/siteseo/common/BaiduAPIDatatable.vue'
export default {
  created () {
    // 获取所有的域名
    this.$post('/domain/bind-infos-list', null).then(response => {
      if (response && response.length > 0) {
        this.domains = response
      } else {
        this.domains = []
      }
    })
    // 获取百度普通收录token
    if (this.form.domainId) {
      this.bandleTokenLoading = true
      this.$post('/externalapi/find-baidu-zztoken', { domainId: this.form.domainId }).then(response => {
        if (response) {
          this.form.zztoken = response.zzToken
          this.form.zzstatus = response.zzStatus
        } else {
          this.form.zztoken = ''
          this.form.zzstatus = -1
        }
      }).then(() => {
        this.bandleTokenLoading = false
      })
    }
    // 获取百度推送记录
    this.$post('/externalapi/baidu-urls', { domainId: -1, status: -1, page: this.page, pagesize: this.pagesize }).then(response => {
      if (response && response.rows && response.rows.length > 0) {
        this.rowsData = response.rows
        this.totalnum = response.total
        this.tableData = initTableData(this.rowsData)
        // console.log(this.tableData)
      } else {
        // this.domains = []
      }
    })
  },
  data () {
    return {
      loading: false,
      activeName: ['1', '2', '3', '4', '5'],
      activeNames: '1',
      formLabelWidth: '120px',
      baiduimg1: baiduimg1,
      baiduimg2: baiduimg2,
      form: {
        domainId: null,
        zztoken: '',
        zzstatus: -1
      },
      domains: null,
      page: 0,
      pagesize: 10,
      totalnum: 0,
      tableData: [],
      rowsData: null,
      dialogTableVisible: false,
      viewData: null,
      // 绑定token的时候
      bandleTokenLoading: false
    }
  },
  watch: {
    'form.domainId': {
      handler (newValue) {
        // 获取百度普通收录token
        if (newValue) {
          this.bandleTokenLoading = true
          this.$post('/externalapi/find-baidu-zztoken', { domainId: newValue }).then(response => {
            if (response) {
              this.form.zztoken = response.zzToken
              this.form.zzstatus = response.zzStatus
            } else {
              this.form.zztoken = ''
              this.form.zzstatus = -1
            }
          }).then(() => {
            this.bandleTokenLoading = false
          })
        }
      }
    }
  },
  computed: {
    bandleDomainStatusHtml () {
      if (this.form && this.form.domainId) {
        if (this.form.zzstatus === 1) {
          return '（ 已通过测试 ）'
        } else {
          return '（ 未通过测试 ）'
        }
      }
      return ''
    },
    bandleDomainStatusStyle () {
      if (this.form && this.form.domainId) {
        if (this.form.zzstatus === 1) {
          return 'color:#67C23A'
        } else {
          return 'color:#F56C6C'
        }
      }
      return ''
    }
  },
  methods: {
    onSubmitData () {
      if (!this.form.domainId) {
        this.$message.error('请选择域名！')
      }
      // if (!this.form.zztoken) {
      //   this.$message.error('token值不能为空！')
      // }
      if (this.form && this.form.domainId) {
        this.$post('/externalapi/save-baidu-zztoken', this.form).then(response => {
          if (response) {
            this.$message.success('保存成功！')
          }
        })
      }
    },
    onSubmitTest () {
      if (!this.form.domainId) {
        this.$message.error('请选择域名！')
      }
      if (this.form && this.form.domainId) {
        this.bandleTokenLoading = true
        // console.log(this.form)
        this.$post('/externalapi/test-baidu-zztoken', {
          domainId: this.form.domainId,
          zztoken: this.form.zztoken
        }).then(rsp => {
          if (rsp && rsp.id && rsp.id > 0) {
            this.form.zzstatus = rsp.zzStatus
          }
        }).then(() => {
          this.bandleTokenLoading = false
        })
      }
    },
    handleCurrentChange (val) {
      // 获取百度推送记录
      this.$post('/externalapi/baidu-urls', { domainId: -1, status: -1, page: val, pagesize: this.pagesize }).then(response => {
        if (response && response.rows && response.rows.length > 0) {
          this.rowsData = response.rows
          this.tableData = initTableData(this.rowsData)
        } else {
          this.domains = []
        }
      })
    },
    viewInfo (baiduUrlsId) {
      let infoItem = this.tableData.find(element => {
        return parseInt(element.baiduUrls.id) === parseInt(baiduUrlsId)
      })

      if (!infoItem) {
        return
      }
      this.viewData = infoItem
      // console.log('this.viewData', this.viewData)
      this.dialogTableVisible = true
    },
    exportToExcel () {

    },
    close () {
      this.activeNames = '1'
      this.dialogTableVisible = false
      this.viewData = null
      this.baiduUrlsTitle = ''
    }
  },
  components: {
    BaiduAPIDatatable
  }
}
function inArray (arr, str) {
  let index = arr.length
  while (index--) {
    if (arr[index] === str) {
      return true
    }
  }
  return false
}
function initTableData (rowsData) {
  let rowsDataInfo = rowsData
  rowsDataInfo.forEach(element => {
    let urlsAll, urlsNotSameSite, urlsNotValid, urlsSuccess
    if (element.baiduUrls.urls) {
      urlsAll = element.baiduUrls.urls.split(/[(\r\n)\r\n]+/)
    } else {
      urlsAll = []
    }
    element.baiduUrls.urlsAll = urlsAll
    element.baiduUrls.urlsAllTotal = urlsAll.length
    if (element.baiduUrls.notSameSite) {
      urlsNotSameSite = element.baiduUrls.notSameSite.split(/[(\r\n)\r\n]+/)
    } else {
      urlsNotSameSite = []
    }
    element.baiduUrls.urlsNotSameSite = urlsNotSameSite
    element.baiduUrls.urlsNotSameSiteTotal = urlsNotSameSite.length

    if (element.baiduUrls.notValid) {
      urlsNotValid = element.baiduUrls.notValid.split(/[(\r\n)\r\n]+/)
    } else {
      urlsNotValid = []
    }
    element.baiduUrls.urlsNotValid = urlsNotValid
    element.baiduUrls.urlsNotValidTotal = urlsNotValid.length
    urlsSuccess = urlsAll.filter(item => {
      return !inArray(urlsNotSameSite, item) && !inArray(urlsNotValid, item)
    })
    element.baiduUrls.urlsSucess = urlsSuccess
    element.baiduUrls.urlsSucessTotal = urlsSuccess.length
  })
  return rowsDataInfo
}
</script>

<style scoped lang="scss">
.seo-baidu-api .tempalte-title {
  font-weight: bold;
  color: #353535;
  font-size: 16px;
  .note {
    font-size: 13px;
    color: #999;
    margin-left: 8px;
    font-weight: normal;
  }
}
.content-p {
  padding: 10px 15px;
  h5 {
    font-size: 15px;
    margin: 0 0 10px;
  }
  p {
    margin-bottom: 15px;
  }
  .note {
    margin-left: 5px;
  }
}
.noticeShowM {
  border-left: 4px solid #409eff;
  padding: 15px;
  font-size: 13px;
  line-height: 1.7;
  background: #f0f8ff;
  margin-bottom: 20px;
}
.group-button {
  text-align: left;
  margin-left: 120px;
}
.requireStar /deep/ .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.totalBox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  .item {
    width: 23%;
    text-align: center;
    padding: 10px 20px;
    background: #f8f8f8;
    color: #555;
    line-height: 1.5;
    .num {
      font-size: 32px;
      color: #111;
    }
  }
}
.dialogDetail /deep/ .el-dialog__body {
  padding-top: 10px;
  padding-bottom: 10px;
}
.errorMessage {
  padding-top: 30px;
  .hh {
    color: #222;
    font-weight: bold;
  }
}
</style>
